import React from 'react';
import { Redirect, Route, Switch, withRouter } from 'react-router-dom';
import { IRoute } from '../../interface';
import Transition from '../transition';

interface IProps extends IRoute {
  app?: boolean; // 是否打包成APP，既启用app模拟跳转
  transition?: boolean; // 开启跳转动画
  page: {
    [index: string]: React.ComponentClass<any>;
  };
}

// 路由注册
const Router: React.SFC<IProps> = ({ app, transition, page, location, history }) => {
  const key: string[] = Object.keys(page);

  const res = (
    <Switch location={location} key={location.pathname}>
      {key.map((item, index) => (
        <Route key={index} path={item} exact={true} component={page[item]} />
      ))}
      <Redirect to={key[0]} />
    </Switch>
  );

  if (transition) {
    const name = app ? (history.action === 'PUSH' ? 'go' : 'back') : 'fade';
    return <Transition name={name}>{res}</Transition>;
  }

  return res;
};

export default withRouter(Router);
